package com.train.user.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.train.user.domain.SysPostCollect;
import com.train.user.mapper.SysPostCollectMapper;
import com.train.user.service.SysPostCollectService;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

/**
* @author train
* @description 针对表【sys_post_collect(动态收藏表)】的数据库操作Service实现
* @createDate 2025-11-28 21:30:00
*/
@Service
public class SysPostCollectServiceImpl extends ServiceImpl<SysPostCollectMapper, SysPostCollect>
    implements SysPostCollectService{

    /**
     * 收藏动态
     */
    @Override
    @Transactional
    public boolean collectPost(Long userId, Long postId) {
        // 检查用户是否已收藏
        if (isPostCollected(userId, postId)) {
            return false; // 已收藏
        }

        // 保存收藏记录
        SysPostCollect collect = new SysPostCollect();
        collect.setUserId(userId);
        collect.setPostId(postId);
        collect.setCreateBy(String.valueOf(userId));
        boolean saved = this.save(collect);
        if (!saved) {
            return false;
        }

        // 增加动态收藏数
        int affectedRows = this.baseMapper.incrementCollectCount(postId);
        return affectedRows > 0;
    }

    /**
     * 取消收藏动态
     */
    @Override
    @Transactional
    public boolean uncollectPost(Long userId, Long postId) {
        // 删除收藏记录
        LambdaQueryWrapper<SysPostCollect> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SysPostCollect::getUserId, userId)
                   .eq(SysPostCollect::getPostId, postId);
        boolean removed = this.remove(queryWrapper);
        if (!removed) {
            return false;
        }

        // 减少动态收藏数
        int affectedRows = this.baseMapper.decrementCollectCount(postId);
        return affectedRows > 0;
    }

    /**
     * 检查用户是否已收藏该动态
     */
    @Override
    public boolean isPostCollected(Long userId, Long postId) {
        int count = this.baseMapper.checkUserCollect(userId, postId);
        return count > 0;
    }
}
